<template>
  <div id="app">
    <div class="form-row">
      <DatePicker v-model="dateRange" @update:selectedDates="handleDateUpdate"></DatePicker>
      <span class="caption">提车门店：</span>
      <Select v-model="borrowFrom" @update:selectedStore="handleSelectedStore1"></Select>
      <span class="caption">归还门店:</span>
      <Select v-model="returnTo" @update:selectedStore="handleSelectedStore2"></Select>
    </div>

    <div class="mb-4">
      <el-button type="primary" @click="fetchData">查看可用车辆</el-button>
    </div>
    <div class="table-container">
      <el-table :data="tableData" class="el-table">
        <el-table-column prop="carModelID" label="车型编号" width="200" />
        <el-table-column prop="carType" label="车型" width="200" />
        <el-table-column prop="brand" label="品牌" width="200" />
        <el-table-column prop="price" label="单价" width="200" />
        <el-table-column prop="amount" label="数量" width="200" />
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button @click="makeReservation(scope.row)">预定</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :v-model="errorDialogVisible" title="错误">
      <span>{{ errorMessage }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="errorDialogVisible = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import DatePicker from "@/components/DatePicker.vue";
import Select from "@/components/Select.vue";
import { useStore } from 'vuex'; // 添加这一行

export default {
  name: 'Reservation',
  components: {
    Select,
    DatePicker
  },
  setup() {
    const store = useStore(); // 添加这一行

    const dateRange = ref([]);
    const borrowFrom = ref('');
    const returnTo = ref('');
    const tableData = ref([]);
    const errorDialogVisible = ref(false);
    const errorMessage = ref('');

    const handleSelectedStore1 = (storeId) => {
      console.log('Selected store ID:', storeId);
      borrowFrom.value = storeId;
    };

    const handleSelectedStore2 = (storeId) => {
      console.log('Selected store ID:', storeId);
      returnTo.value = storeId;
    };

    const fetchData = async () => {
      if (!borrowFrom.value || !dateRange.value[0]) {
        errorMessage.value = 'Please select a valid location and date.';
        errorDialogVisible.value = true;
        return;
      }
      try {
        const startDate = formatDate(dateRange.value[0]);
        const response = await axios.get(`/Reservation/StoreID/${borrowFrom.value}/From/${startDate}`);
        if (response.data.statusCode === 200) {
          tableData.value = response.data.data.map(item => ({
            carModelID: item.carModel.carModelID,
            carType: item.carModel.carType,
            brand: item.carModel.brand,
            price: item.carModel.price,
            amount: item.amount
          }));
        } else {
          errorMessage.value = `Error fetching data: ${response.data.message}`;
          errorDialogVisible.value = true;
        }
      } catch (error) {
        errorMessage.value = `Error fetching data: ${error.message}`;
        errorDialogVisible.value = true;
      }
    };

    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    const handleDateUpdate = (dates) => {
      if (dates && dates.length === 2) {
        const startDateFormatted = formatDate(dates[0]);
        const endDateFormatted = formatDate(dates[1]);
        console.log(`Formatted Start Date: ${startDateFormatted}, End Date: ${endDateFormatted}`);
        dateRange.value = [new Date(startDateFormatted), new Date(endDateFormatted)];
      }
    };

    const makeReservation = async (row) => {
      const token = store.getters['auth/getToken'];
      if (!token) {
        window.location.href = '/login';  // 跳转到登录页面
        return;
      }
      const reservation = {
        carModelID: row.carModelID,
        expectedCheckoutStoreID: borrowFrom.value,
        expectedCheckoutTime: formatDate(dateRange.value[0]),
        expectedReturnStoreID: returnTo.value,
        expectedReturnTime: formatDate(dateRange.value[1]),
        renewalPermission: "",
        reservationID: "",
        reservationStatus: "",
        userID: "",
      };
      try {
        const response = await axios.post('/api/Reservation', reservation, {
          headers: {
            'token': token
          }
        });
        if (response.data.statusCode === 200) {
          ElMessage.success('Reservation successful!');
          console.log('借车成功:', response.data.message);
        } else {
          errorMessage.value = `${response.data.message}`;
          errorDialogVisible.value = true;
        }
      } catch (error) {
        errorMessage.value = ` ${error.message}`;
        errorDialogVisible.value = true;
      }
    };

    return {
      dateRange,
      borrowFrom,
      returnTo,
      tableData,
      fetchData,
      handleSelectedStore1,
      handleSelectedStore2,
      handleDateUpdate,
      makeReservation,
      errorDialogVisible,
      errorMessage
    };
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.caption {
  display: inline-block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
  padding-left: 10px;
  padding-right: 10px;
}

.mb-4 {
  display: block;
  text-align: center;
  margin-bottom: 1rem;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-bottom: 20px;
}

.table-container {
  text-align: center;
  margin: 0 auto;
  width: 80%;
}

.el-table th, .el-table td {
  text-align: center;
}

.el-table {
  width: 100%;
}
</style>